# -*- coding: UTF-8 -*-
"""
@author:林健
@file:DingTalk_msg_warn.py
@time:2021/04/02
"""
import base64
import hashlib
import hmac
import time
import urllib.parse

import requests
import json


server_list = {
    "paoding":{
        "文本发货":{
            "url":"https://bd-inner.amh-group.com/paoding/text_cargo_now",
            "type":"POST",
            "data":{
                "sentence": "明天早上8点从天津市武清区王庆坨镇尤张堡村，装钢板5吨左右，占10方位置，需要6米8的平板车，到宁波镇海区万达物流园，后天晚上10点前卸货"
            }
        },
        "备注信息提取":{
            "url":"https://bd-inner.amh-group.com/paoding/info_extraction",
            "type":"POST",
            "data":{
                "description": "从安徽六安金寨到湖南长沙望城，运100吨的袋装铁矿石，估计有30方左右，需要13米5高栏车或者9米6平板车，一装两卸，运费到付，现金2000块钱，平台付定金200块钱吧，下午2点前都能装，现在就能过来，记得早点去，明天上午12点前到就行，不押车，也不超重，价格美丽！",
                 "options": []
}
        },
        "货名结构化解析":{
            "url":"https://bd-inner.amh-group.com/paoding/cargo_name_parse",
            "type":"POST",
            "data":{
                "cargoName": "散装铝土矿"
            }
        },
        "货名结构化解析v2":{
            "url":"https://bd-inner.amh-group.com/paoding/cargo_name_parse_v2",
            "type":"POST",
            "data":{
                "cargoName": "散装铝土矿"
            }
        },
        "导航地址文本识别":{
            "url":"https://bd-inner.amh-group.com/paoding/navigation_address_identify",
            "type":"POST",
            "data":{
                "inputText": "今天下午3点在武汉火车站南广场装货"
            }
        },
        "导航地址文本识别（短途）":{
            "url":"https://bd-inner.amh-group.com/paoding/navigation_address_identify",
            "type":"POST",
            "data":{
                "inputText": "我的地址是.江西省鹰潭市月湖区四海路金鹰名仕园A座1704号.联系人:何莉萍.电话.13970178708",
                "shortDistance":"1.csv"
            }
        },
        "中台标签接口":{
            "url":"https://bd-inner.amh-group.com/paoding/middle_ground_label",
            "type":"POST",
            "data":{
                "sentence": "一装一卸, 超高, 需雨布， 要国五车， 栏杆可拆，今天装明天卸，装3小时，有禁区"
            }
        }
    },
    "cangjie":{
        "标准货名": {
            "url": "https://bd-inner.amh-group.com/cangjie_gateway/cargo_name_identify",
            "type": "POST",
            "data": {  "cargoName": "我想运苹果","Transfer": 0}
        },
        "绿色货源": {
            "url": "https://bd-inner.amh-group.com/cangjie_gateway/cargo_filter_web_v4",
            "type": "POST",
            "data": {"cargoName": "","packType": "运一车苹果","payMethod": "运一车苹果","drivingGuide": "运一车苹果","loadAddress":"运一车苹果","unloadAddress":"运一车苹果","comment": "卧槽泥马勒戈壁"}
        },
        "论坛敏感词": {
            "url": "https://bd-inner.amh-group.com/cangjie_gateway/great_wall",
            "type": "POST",
            "data": {"cargoName": "今天是个好天气","packType": "-1.csv","payMethod": "-1.csv","drivingGuide": "-1.csv","loadAddress": "-1.csv","unloadAddress": "-1.csv","comment": "-1.csv"}
        },
        "语音发货": {
            "url": "https://bd-inner.amh-group.com/cangjie_gateway/truck_now?sentence=栖霞到浦东，平板16米左右。",
            "type": "get",
            "data":{},
        },
        "手机号判断": {
            "url": "https://bd-inner.amh-group.com/cangjie_gateway/phone_identification",
            "type": "POST",
            "data": {"shipper_sentence": "#189。#对189。#卸货打款三天之内找到这。#189#1771。#2957。","driver_sentence":"啊#你杭州到北京拉什么活？#给多少钱？啊#那是三方承商是哪家呀#啊#拖#托普啊哈#啊#嗯#能不能多给点？"}
        },

    },
    "athena":{
        "群体意图": {
            "url": "https://bd-inner.amh-group.com/athena/knowledge_management_v2",
            "type": "POST",
            "data": {"id":[1,2]}
        },
        "行为上下文": {
            "url": "https://bd-inner.amh-group.com/athena/action_sequence?userId=123231212",
            "type": "get",
            "data": {}
        },
        "问题预测": {
            "url": "https://bd-inner.amh-group.com/athena/forecast_problem?pageNum=0&pageSize=100",
            "type": "get",
            "data": {}
        },
        "未知问题及对应一二级标签": {
            "url": "https://bd-inner.amh-group.com/athena/potential_questions?pageNum=0&pageSize=100",
            "type": "get",
            "data":{},
        },
        "推荐装卸货地": {
            "url": "https://bd-inner.amh-group.com/athena/shipments_address_recommend",
            "type": "POST",
            "data": {"userId":"12345678910"}
        },
        "行为页面知识配置": {
            "url": "https://bd-inner.amh-group.com/athena/user_action_management?pageNum=0&pageSize=100",
            "type": "get",
            "data": {}
        },
        "推荐货物": {
            "url": "https://bd-inner.amh-group.com/athena/shipments_cargo_recommend",
            "type": "POST",
            "data": {"userId":"1234567","loadProvinceId":"1.csv","loadCityId":"2","loadDistrictId":"3","unloadProvinceId":"4","unloadCityId":"5","unloadDistrictId":"6"}
        },
    }
}

def get_http_result(url,type="POST",data={}):
    post_body = data
    headers = {
        'Content-Type': "application/json"
    }

    try:
        if type == "POST":
            req = requests.post(url, data=json.dumps(post_body), headers=headers)
        else:
            req = requests.get(url)
        if req.status_code == 200:
            return 1
        else:
            return 0
    except Exception as e:
        return 0








class DingTalkWarn:
    """钉钉消息通知"""

    def __init__(self):
        # 安全设置使用加签方式
        timestamp = str(round(time.time() * 1000))
        secret = 'SEC595668dce05422c36124f4c2d7a2e714742a0cdbb78b49df78d5acfa18ce7070'
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

        # webhook地址
        webhook = 'https://oapi.dingtalk.com/robot/send?access_token=753a87e9c5706501c20c20cf7f5154c0970aafdcf0a9c28a19a0cbe71f80a063'
        self.webhook = "{}&timestamp={}&sign={}".format(webhook, timestamp, sign)
        # 配置请求headers
        self.headers = {
            "Content-Type": "application/json",
            "Charset": "UTF-8"  # 发起POST请求时，必须将字符集编码设置成UTF-8。
        }

    def send_text_msg(self, content, at_mobiles=None, is_at_all=False):
        """
        发送text型文本数据
        :param content: 消息内容
        :param at_mobiles: 传入列表类型数据，@出现在列表中的电话联系人，如果群里没有该联系人，则不会@（可选参数）
        :param is_at_all: 是否@所有人，默认不艾特（可选参数）
        :return:
        """
        message = {
            "msgtype": "text",  # 消息类型
            "text": {
                "content": content
            },
            "at": {
                "atMobiles": at_mobiles,
                "isAtAll": is_at_all
            }
        }
        self.send_req(message)  # 发送消息


    def send_req(self, message):
        """
        发送请求
        :param message: 你的消息体
        :return:
        """
        # 将请求数据进行json数据封装
        form_data = json.dumps(message)
        # 发起请求
        res_info = requests.post(url=self.webhook, headers=self.headers, data=form_data)
        # 打印返回的结果
        print('邮件发送结果:', res_info.json())
        print('通知成功！' if (res_info.json())['errmsg'] == 'ok' else '通知失败！')


def check_services():
    result = []
    for (service,apis) in server_list.items():
        success_count = 0
        error_apis = []
        for (api_name,api_info) in apis.items():
            code = 0
            try_count = 3
            while code == 0 and try_count >0:
                code = get_http_result(api_info['url'],api_info["type"],api_info["data"])
                try_count -= 1
            if code  == 1 :
                success_count += 1
            else:
                error_apis.append(api_name+":"+api_info['url'])
        if error_apis:
            service_str = "%s的%s个服务正常,%s个服务异常,异常接口如下：\n%s" % (service,str(success_count),str(len(error_apis)),"\n".join(error_apis))
            result.append(service_str)


    if result :
        result_str = "\n\n".join(result)
        DingTalkWarn().send_text_msg(result_str)









if __name__ == '__main__':
    """测试发送消息"""
    check_services()


